//
//  BHSportCreateClockViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/7/16.
//  创建打卡

import UIKit

class BHSportCreateClockViewController: BHBaseViewController {

    var refreshPreviewBlock:(() -> Void)?
    
    
    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .plain)
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight-UIScreen.safeBottomHeight-10-44-10)
        view.delegate = self
        view.dataSource = self
        view.backgroundColor = .white

        return view
    }()
    
    lazy var createBtn: UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.frame = CGRect(x: 16, y: UIScreen.height-UIScreen.safeBottomHeight-10-44, width: UIScreen.width-32, height: 44)
        btn.backgroundColor = .color_34CE98
        btn.setTitle("立即创建", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
        btn.addTarget(self, action: #selector(createClockNowAct), for: .touchUpInside)
        btn.addLayerCorner(22, 0, .white)
        return btn
    }()
    
    lazy var choseHourMinPicker: BHHourMinPicker = {
        let view = BHHourMinPicker.init(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height))
        return view
    }()
    
    lazy var choseYearMonthDayPicker: BHYearMonthDayPicker = {
        let view = BHYearMonthDayPicker.init(frame:  CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height))
        return view
    }()
    
    // 不为空的时候就是编辑
    var model: BHSportSignDetailModel? {
        didSet {
            if model == nil {
                return
            }
            
            self.titleName = model?.target ?? ""
            self.planText = model?.plan ?? ""
            self.startDay = model?.startTime ?? ""
            self.endDay = model?.endTime ?? ""
            for planModel in model!.planArray {
                self.timeArray.append(planModel.clockTime)
            }
            
            self.tableView.reloadData()
        }
    }
    
    
    fileprivate var titleName: String = ""
    fileprivate var planText: String = ""
    fileprivate var timeArray: [String] = []
    fileprivate var startDay: String = ""
    fileprivate var endDay: String = ""
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.bh_navigationBar.title_label.text = "创建打卡内容"
        self.view.addSubview(self.tableView)
        self.view.addSubview(self.createBtn)
        self.view.addSubview(self.choseHourMinPicker)
        self.view.addSubview(self.choseYearMonthDayPicker)
        self.tableView.regiseterNib(nibName: "BHSportCreateTitleTableViewCell")
        self.tableView.regiseterNib(nibName: "BHSportCreatePlanTableViewCell")
        self.tableView.regiseterNib(nibName: "BHSportCreateStartAndEndCell")
        self.tableView.regiseterNib(nibName: "BHSportCreateDayTimeCell")
        self.tableView.regiseterNib(nibName: "BHSportCreateAddedTimeCell")
        
        
        self.choseHourMinPicker.didPickerChoseTimeActBlock = {[weak self] time in
            if self?.timeArray.contains(time) == true {
                BHToast.toast(text: "打卡时间已存在");
                return
            }
            self?.timeArray.append(time)
            self?.tableView.reloadData()
        }
        
        self.choseYearMonthDayPicker.didPickerChoseDayActBlock = { [weak self] (day,type) in
            if type == 0 {
                self?.startDay = day
            }else {
                self?.endDay = day
            }
            self?.tableView.reloadData()
        }

        if self.model != nil {
            self.bh_navigationBar.title_label.text = "修改打卡内容"
            self.createBtn.setTitle("立即修改", for: .normal)
        }
    }
    
    @objc func createClockNowAct() {
        if self.titleName.isEmpty == true {
            BHToast.toast(text: "请输入目标")
            return
        }
        if self.planText.isEmpty == true {
            BHToast.toast(text: "请输入计划")
            return
        }
        
        if self.startDay.isEmpty == true {
            BHToast.toast(text: "请选择开始时间")
            return
        }
        if self.endDay.isEmpty == true {
            BHToast.toast(text: "请选择结束时间")
            return
        }
        if self.timeArray.count == 0 {
            BHToast.toast(text: "请添加打卡时间")
            return
        }
        if self.model == nil {
            self.createTargetService()
        }else {
            self.editeTargetService()
        }
    }

}
extension BHSportCreateClockViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 3
        }else {
            return 1+self.timeArray.count
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            if indexPath.row == 1 {
                return 94
            }else {
                return 53
            }
        }
        return 53

    }
  
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.view.endEditing(true)
    }
}

extension BHSportCreateClockViewController: UITableViewDelegate {
  
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "BHSportCreateTitleTableViewCell", for: indexPath) as! BHSportCreateTitleTableViewCell
                cell.title_textFiled.text = self.titleName
                cell.textFieldDidEndEditingBlock = { [weak self] text in
                    self?.titleName = text
                }
                return cell
            }else if indexPath.row == 1 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "BHSportCreatePlanTableViewCell", for: indexPath) as! BHSportCreatePlanTableViewCell
                cell.text_view.text = self.planText
                cell.place_label.isHidden = self.planText.isEmpty == false
                cell.textViewDidEndEditingBlock = {[weak self] text in
                    self?.planText = text
                }
                return cell
            }else {
                let cell = tableView.dequeueReusableCell(withIdentifier: "BHSportCreateStartAndEndCell", for: indexPath) as! BHSportCreateStartAndEndCell
                
                cell.startTimeBtn.isSelected = !self.startDay.isEmpty
                cell.endTimeBtn.isSelected = !self.endDay.isEmpty
                if self.startDay.isEmpty {
                    cell.startTimeBtn.setTitle("开始时间", for: .normal)
                }else {
                    cell.startTimeBtn.setTitle(self.startDay, for: .selected)
                }
                
                if self.endDay.isEmpty {
                    cell.endTimeBtn.setTitle("结束时间", for: .normal)
                }else {
                    cell.endTimeBtn.setTitle(self.endDay, for: .selected)
                }
                
                cell.startTimeBtn.addBtnAction(action: {[weak self] (_) in
                    self?.view.endEditing(true)
                    self?.choseYearMonthDayPicker.type = 0
                    self?.choseYearMonthDayPicker.show()
                }, for: .touchUpInside)
                
                cell.endTimeBtn.addBtnAction(action: {[weak self] (_) in
                    self?.view.endEditing(true)
                    self?.choseYearMonthDayPicker.type = 1
                    self?.choseYearMonthDayPicker.show()
                }, for: .touchUpInside)
                return cell
            }
            
        }else {
            return self.cellForDayTime(indexPath: indexPath)
        }
        
    }
}


extension BHSportCreateClockViewController {
    func cellForDayTime(indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHSportCreateDayTimeCell", for: indexPath) as! BHSportCreateDayTimeCell
            if self.timeArray.count >= 6 {
                cell.add_time_btn.isHidden = true
            }else {
                cell.add_time_btn.isHidden = false
            }
            cell.add_time_btn.addBtnAction(action: {[weak self] (_) in
                self?.choseHourMinPicker.show()
            }, for: .touchUpInside)
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHSportCreateAddedTimeCell", for: indexPath) as! BHSportCreateAddedTimeCell
            cell.time_label.text = self.timeArray[indexPath.row-1]
            cell.del_time_btn.addBtnAction(action: {[weak self] (_) in
                self?.timeArray.remove(at: indexPath.row-1)
                
                self?.tableView.reloadData()
            }, for: .touchUpInside)
            return cell
        }
    }
}

// MARK: 创建打卡内容
extension BHSportCreateClockViewController {
    func createTargetService()  {
        let dic = self.appendDic()
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.post(url: String.sport_create_target_url, paramters: dic) {[unowned self] (success, errorMsg, responseDic) in
            SVProgressHUD.dismiss()
            if success == true{
                BHToast.toast(text: "创建成功")
                DispatchQueue.main.asyncAfter(deadline: .now()+1.5) {
                    self.navigationController?.popViewController(animated: true)
                }
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
        
    }
    
    func appendDic() -> [String:Any] {
        var dic: [String:Any] = [:]
        dic["target"] = self.titleName
        dic["plan"] = self.planText
        dic["startTime"] = self.startDay
        dic["endTime"] = self.endDay
        dic["clockTimeList"] = self.timeArray
        if self.model != nil {
            dic["id"] = self.model?.targetId
        }
        return dic
    }
}



// MARK: 编辑打卡内容
extension BHSportCreateClockViewController {
    func editeTargetService()  {
        let dic = self.appendDic()
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.put(url: String.sport_edite_target_url, paramters: dic) {[unowned self] (success, errorMsg, responseDic) in
            SVProgressHUD.dismiss()
            if success == true{
                self.refreshPreviewBlock?()
                BHToast.toast(text: "编辑成功")
                DispatchQueue.main.asyncAfter(deadline: .now()+1.5) {
                    self.navigationController?.popViewController(animated: true)
                }
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
        
    }
    
  
}
